import React from "react";
import { Spin } from 'antd';

export class AsyncComponent extends React.Component<IAsyncComponentProps> {

    private unmount = false

    state = {
        component: null
    }

    render() {
        const c = this.state.component
        if (c == null) {
            return <Spin />
        }
        const CC = (c["default"] ? c["default"] : c[Object.keys(c)[0]]) as any
        this.props.onLoaded?.()
        return <CC {...this.props} />
    }

    async componentDidMount() {
        this.props.beforeLoad?.()
        const c = await this.props.importFunc()
        if (!this.unmount) {
            this.setState({
                component: c
            })
        }
    }

    componentWillUnmount() {
        this.unmount = true
    }

}

export interface IAsyncComponentProps {
    /**动态 import 的模块，例如：()=>import("./page/folder/module")*/
    importFunc: () => Promise<any>
    /**异步组件加载前触发 */
    beforeLoad?: () => void
    /**页面加载完成事件 */
    onLoaded?: () => void
}